package hust.ioic.oa.view.action;

import hust.ioic.oa.base.BaseAction;
import hust.ioic.oa.domain.Comment;
import hust.ioic.oa.domain.Department;
import hust.ioic.oa.domain.Function;
import hust.ioic.oa.domain.KnowType;
import hust.ioic.oa.domain.MessageQuene;
import hust.ioic.oa.domain.Operator;
import hust.ioic.oa.domain.Rdfile;
import hust.ioic.oa.domain.Role;
import hust.ioic.oa.domain.Text;
import hust.ioic.oa.qilin.utils.GetDate;
import hust.ioic.oa.utils.FTPUtils;
import hust.ioic.oa.utils.KnowTypeUtils;
import hust.ioic.oa.utils.MsgInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Collections;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

@Controller
@Scope("prototype")
public class RdfileAction extends BaseAction<Rdfile> {
	private Integer knowTypeId;
	private Integer rid;
	private Integer rdfileId;
	private String content;
	private Integer[] departmentIds;
	private Integer[] knowTypeIds;
	private String textname;
	private File fileField; // 上传的文件
	private String fileFieldFileName; // 上传的附件的名称
	private Integer recevieId; // 附件审批者id
	private String newpassword;
	GetDate gd = new GetDate();

	// 展示文件
	public String list() {
		KnowType kn = knowTypeService.getById(knowTypeId);
		Set<Rdfile> rdfiles = kn.getRdfiles();
		List<Rdfile> articleList = new ArrayList<Rdfile>();
		List<Rdfile> dfileList = new ArrayList<Rdfile>();
		for (Rdfile r : rdfiles) {
			if (r.getType() == 0 && r.getDisplay() == 1) {
				articleList.add(r);
			} else if (r.getType() == 1 && r.getDisplay() == 1) {
				dfileList.add(r);
			}
		}
		List<Operator> operatorList = operatorService.findAll();
		ActionContext.getContext().put("y", knowTypeId);
		Collections.sort(articleList);
		Collections.sort(dfileList);
		ActionContext.getContext().put("articleList", articleList);
		ActionContext.getContext().put("dfileList", dfileList);
		ActionContext.getContext().put("operatorList", operatorList);
		return "list";
	}

	// 进入我的文件
	public String myfileList() {
		Operator o = getCurrentOperator();

		List<Rdfile> rdfileList = rdfileService.getFilesByOperator(o.getId());
		List<Rdfile> articleList = new ArrayList<Rdfile>();
		List<Rdfile> dfileList = new ArrayList<Rdfile>();
		for (Rdfile r : rdfileList) {
			if (r.getType() == 0) {
				articleList.add(r);
			} else if (r.getType() == 1) {
				dfileList.add(r);
			}
		}
		ActionContext.getContext().put("y", -1);
		Collections.sort(articleList);
		Collections.sort(dfileList);
		ActionContext.getContext().put("articleList", articleList);
		ActionContext.getContext().put("dfileList", dfileList);
		List<Operator> operatorList = operatorService.findAll();
		ActionContext.getContext().put("operatorList", operatorList);
		return "myfileList";
	}

	/**
	 * 
	 * 更改页面
	 * 
	 * @return
	 */
	public String editUI() {
		List<KnowType> knowTypeList = knowTypeService.findTopList();
		ActionContext.getContext().put("knowTypeList", knowTypeList);

		Rdfile rdfile = rdfileService.getById(rid);
		ActionContext.getContext().getValueStack().push(rdfile);
		if (rdfile.getKnowTypes() != null) {
			knowTypeIds = new Integer[rdfile.getKnowTypes().size()];
			int index = 0;
			for (KnowType privi : rdfile.getKnowTypes()) {
				knowTypeIds[index++] = privi.getId();
			}
		}
		if (rdfile.getType() == 0) {
			Text t = textService.getById(rdfile.getTextId());
			textname = t.getName();
			content = t.getContent();
		}
		return "saveUI";
	}

	/**
	 * 
	 * 更改方法
	 * 
	 * @return
	 */
	public String edit() {
		Rdfile rdfile = rdfileService.getById(model.getId());
		rdfile.setName(textname);
		rdfile.setRemark(model.getRemark());
		if (knowTypeIds != null) {
			Set<KnowType> knowTypes = new HashSet<>();
			for (int i = 0; i < knowTypeIds.length; i++) {
				KnowType k = knowTypeService.getById(knowTypeIds[i]);
				knowTypes.add(k);
			}
			rdfile.setKnowTypes(knowTypes);
		}
		if (rdfile.getType() == 0) {
			Text t = textService.getById(rdfile.getTextId());
			t.setName(textname);
			t.setContent(content);
			textService.update(t);
		}
		rdfileService.update(rdfile);
		return "toList";
	}

	public String knowList() {
		List<KnowType> all = knowTypeService.findAll();
		for (KnowType k : all) {
			Set<Rdfile> rdfiles = k.getRdfiles();
			int num = 0;
			for (Rdfile r : rdfiles) {
				if (r.getDisplay() == 1) {
					num++;
				}
			}
			k.setFileNum(num);
			knowTypeService.update(k);
		}
		List<KnowType> knowTypeList = knowTypeService.findTopList();
		ActionContext.getContext().put("knowTypeList", knowTypeList);
		return "knowList";
	}

	// 查看页面
	public String view() {
		Rdfile rd = rdfileService.getById(rid);

		if (rd == null) {
			ActionContext.getContext().put("message", "知识已删除！");
			return "message";
		}

		List<Operator> operatorList = operatorService.findAll();
		List<Comment> commmentList = commentService.getByFile(rid);
		ActionContext.getContext().put("operatorList", operatorList);
		ActionContext.getContext().put("commmentList", commmentList);
		if (rd.getType() == 0) {
			Text text = textService.getById(rd.getTextId());
			ActionContext.getContext().getValueStack().push(text);
			return "article";
		} else {
			ActionContext.getContext().getValueStack().push(rd);
			return "downLoad";
		}

	}

	public String addCommentUI() {
		Rdfile rd = rdfileService.getById(rdfileId);
		ActionContext.getContext().getValueStack().push(rd);
		return "addCommentUI";
	}

	public String addComment1UI() {
		Rdfile rd = rdfileService.getByTextId(rdfileId);
		if (rd == null) {
			ActionContext.getContext().put("message", "知识已删除！");
			return "message";
		}

		ActionContext.getContext().getValueStack().push(rd);
		return "addCommentUI";
	}

	public String addComment() {
		Rdfile rd = rdfileService.getById(model.getId());
		if (rd == null) {
			ActionContext.getContext().put("message", "知识已删除！");
			return "message";
		}
		Comment c = new Comment();
		c.setRdfileId(model.getId());
		c.setOperatorId(getCurrentOperator().getId());

		c.setCreateTime(gd.getCurrentTime());
		c.setContent(content);
		commentService.save(c);

		List<Operator> operatorList = operatorService.findAll();
		List<Comment> commmentList = commentService.getByFile(model.getId());
		ActionContext.getContext().put("operatorList", operatorList);
		ActionContext.getContext().put("commmentList", commmentList);
		if (rd.getType() == 0) {
			Text text = textService.getById(rd.getTextId());
			ActionContext.getContext().getValueStack().push(text);
			return "article";
		} else {
			ActionContext.getContext().getValueStack().push(rd);
			return "downLoad";
		}
	}

	// 上传页面
	public String upload() {
		// 构建知识分类树
		List<KnowType> knowTypeList = knowTypeService.findTopList();
		// 构建审阅者信息
		Function function = functionService
				.findByUrl("/messageQuene_checkList");
		Set<Role> roleSet = function.getRoles();
		List<Operator> operatorList = new ArrayList<Operator>();
		for (Role role : roleSet) {
			Set<Operator> operators = role.getOperators();
			operatorList.addAll(new ArrayList<Operator>(operators));
		}
		// 若当前用户拥有审批权限，则在list中去掉该用户
		Iterator<Operator> it = operatorList.iterator();
		while (it.hasNext()) {
			// 通过id属性判断是否为当前登录用户
			if (it.next().getId().equals(getCurrentOperator().getId())) {
				it.remove();
			}
		}

		ActionContext.getContext().put("knowTypeList", knowTypeList);
		ActionContext.getContext().put("operatorList", operatorList);
		return "upLoad";
	}

	public String add() {

		// 校验上传的附件的文件名是否重复
		Rdfile rdFile = rdfileService.getByName(fileFieldFileName);
		if (rdFile != null) {
			ActionContext.getContext().put("result",
					new MsgInfo(1, "上传失败，文件名重复，请更改文件名后再上传！"));
			return "result";
		}

		// 校验创建的文章的标题是否重复
		Rdfile rdFileText = rdfileService.getByName(textname);
		if (rdFileText != null) {
			ActionContext.getContext().put("result",
					new MsgInfo(1, "标题重复，请更改标题后再保存"));
			return "result";
		}

		Rdfile rd = new Rdfile();
		if ("".endsWith(textname)) {
			rd.setType(1);
			rd.setName(fileFieldFileName);
			MsgInfo msgInfo;
			// 将附件上传到ftp服务器
			try {
				InputStream in = new FileInputStream(fileField);
				FTPUtils ftpUtils = new FTPUtils();
				msgInfo = ftpUtils.ftpUploadFile(fileFieldFileName, in);
			} catch (FileNotFoundException e) {

				e.printStackTrace();
				ActionContext.getContext().put("result",
						new MsgInfo(1, "系统异常，请联系管理员"));
				return "result";
			}
			// 上传出现问题
			if (msgInfo.getCode() != 0) {
				// 将异常信息返回给前台
				ActionContext.getContext().put("result", msgInfo);
				return "result";
			}
			ActionContext.getContext().put("result", msgInfo);
		} else {
			// new一个文章对象
			Text t = new Text();
			t.setContent(content);
			t.setName(textname);
			textService.save(t); // 保存文章对象

			rd.setTextId(t.getId());
			rd.setType(0);
			rd.setName(textname);
		}
		rd.setOperatorId(getCurrentOperator().getId());
		rd.setCreateTime(gd.getCurrentTime());
		rd.setDisplay(0);
		rd.setRemark(model.getRemark());
		rd.setPassword(DigestUtils.md5Hex(model.getPassword()));
		if (knowTypeIds != null) {
			Set<KnowType> knowTypes = new HashSet<>();
			for (int i = 0; i < knowTypeIds.length; i++) {
				KnowType k = knowTypeService.getById(knowTypeIds[i]);
				knowTypes.add(k);
			}
			rd.setKnowTypes(knowTypes);
		}
		rdfileService.save(rd);

		MessageQuene m = new MessageQuene();
		m.setRdfileId(rd.getId());
		m.setSendId(getCurrentOperator().getId());
		// 初始置为0
		m.setStatus(0);
		m.setSendTime(gd.getCurrentTime());
		m.setRecevieId(recevieId);
		m.setRequestRemark("请求上传文件" + rd.getName());
		messageQueneService.save(m);
		ActionContext.getContext().put("result", new MsgInfo(0, ""));

		return "result";
	}

	public String delete() {
		Rdfile rdfile = rdfileService.getById(model.getId());
		messageQueneService.deleteByFile(model.getId());
		commentService.deleteByFile(model.getId());
		if (rdfile.getTextId() != null) {
			textService.delete(rdfile.getTextId());
		}
		rdfileService.delete(model.getId());
		return "tofileList";
	}

	public String setDepartmentUI() {
		Rdfile rd = rdfileService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(rd);
		if (rd.getDepartments() != null) {
			departmentIds = new Integer[rd.getDepartments().size()];
			int index = 0;
			for (Department privi : rd.getDepartments()) {
				departmentIds[index++] = privi.getId();
			}
		}
		List<Department> departmentList = departmentService.findTopList();
		ActionContext.getContext().put("departmentList", departmentList);
		return "setDepartmentUI";
	}

	public String setDepartment() {
		Rdfile rd = rdfileService.getById(model.getId());
		Set<Department> departments = new HashSet<>();
		if (departmentIds != null) {
			for (int i = 0; i < departmentIds.length; i++) {
				Department d = departmentService.getById(departmentIds[i]);
				departments.add(d);
			}
			rd.setDepartments(departments);
			rdfileService.update(rd);
		}

		return "tofileList";
	}

	public String setPassword() {
		Rdfile rd = rdfileService.getById(model.getId());
		rd.setPassword(DigestUtils.md5Hex(newpassword));
		rdfileService.update(rd);
		return "tofileList";
	}

	public String setPasswordUI() {
		Rdfile rd = rdfileService.getById(model.getId());
		ActionContext.getContext().getValueStack().push(rd);
		return "setPasswordUI";
	}

	public Integer getKnowTypeId() {
		return knowTypeId;
	}

	public void setKnowTypeId(Integer knowTypeId) {
		this.knowTypeId = knowTypeId;
	}

	public Integer getRid() {
		return rid;
	}

	public void setRid(Integer rid) {
		this.rid = rid;
	}

	public File getFileField() {
		return fileField;
	}

	public void setFileField(File fileField) {
		this.fileField = fileField;
	}

	public String getFileFieldFileName() {
		return fileFieldFileName;
	}

	public void setFileFieldFileName(String fileFieldFileName) {
		this.fileFieldFileName = fileFieldFileName;
	}

	public Integer getRecevieId() {
		return recevieId;
	}

	public void setRecevieId(Integer recevieId) {
		this.recevieId = recevieId;
	}

	public Integer getRdfileId() {
		return rdfileId;
	}

	public void setRdfileId(Integer rdfileId) {
		this.rdfileId = rdfileId;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Integer[] getDepartmentIds() {
		return departmentIds;
	}

	public void setDepartmentIds(Integer[] departmentIds) {
		this.departmentIds = departmentIds;
	}

	public String getTextname() {
		return textname;
	}

	public void setTextname(String textname) {
		this.textname = textname;
	}

	public Integer[] getKnowTypeIds() {
		return knowTypeIds;
	}

	public void setKnowTypeIds(Integer[] knowTypeIds) {
		this.knowTypeIds = knowTypeIds;
	}

	public String getNewpassword() {
		return newpassword;
	}

	public void setNewpassword(String newpassword) {
		this.newpassword = newpassword;
	}

}
